<template>
  <div>
    <Head />
    <div class="cart-area">
      <div class="container">
        <div class="row">
          <div class="Breadcrumb">
            <el-page-header title="返回" content="我的购物车" @back="goBack" />
          </div>
          <div class="table">
            <el-table
              ref="multipleTable"
              v-loading="loading"
              :data="tableData"
              tooltip-effect="dark"
              style="width: 1140px; border-radius: 10px; margin-top: 30px;"
              :header-cell-style="{background: '#faf6f6'}"
              :row-style="{background: '#faf6f6'}"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                align="center"
                type="selection"
              />
              <el-table-column
                label="封面"
                fixed="left"
                align="center"
              >
                <template slot-scope="scope">
                  <router-link :to="{path: '/bookDetails', name: 'bookDetails', query: { id: scope.row.bookId } }">
                    <img
                      :src="scope.row.cover"
                      :style="{width: '140px', height: '140px', borderRadius: '10px'}"
                    >
                  </router-link>
                </template>
              </el-table-column>
              <el-table-column
                prop="bookName"
                label="商品名称"
                align="center"
              />
              <el-table-column
                label="数量"
                align="center"
                fixed="right"
              >
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.bookNumber" size="small" :min="1" :max="999" @change="handleChange(scope.row)" />
                </template>
              </el-table-column>
              <el-table-column
                prop="price"
                label="单价/￥"
                align="center"
                fixed="right"
              />
              <el-table-column
                label="总价/￥"
                align="center"
                fixed="right"
              >
                <template slot-scope="scope">
                  <span style="color: red;font-weight: bold">{{ scope.row.total }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="margin-top: 30px; margin-right: 20px; font-size: 20px; color: #52b788; font-weight: bold">总计： ￥{{ totalCost }}</div>
          <div class="btn">
            <el-button style="margin: 30px 20px" type="danger" @click="removeItems(), clickHandler($event)">移出购物车</el-button>
            <el-button style="margin: 30px 20px" @click="addOrder(), clickHandler($event)">生成订单</el-button>
          </div>
        </div>
      </div>
    </div>
    <Foot />
  </div>
</template>

<script>
import userApi from '@/api/user'
import Head from '@/views/user/component/Head'
import Foot from '@/views/user/component/Footer'

export default {
  components: { Head, Foot },
  data() {
    return {
      tableData: [],
      multipleSelection: [],
      input: '',
      user: false,
      userId: 0,
      status: false,
      loading: true
    }
  },
  computed: {
    totalCost: function() {
      let cost = 0.0
      // 统计勾选项的总金额
      if (this.multipleSelection) {
        this.multipleSelection.forEach(checked => {
          cost += checked.total
        })
        return cost
      } else return 0.0
    }
  },

  created() {
    this.initData()
  },

  methods: {
    // 勾选
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 金额实时变化
    handleChange(item) {
      const { bookId, bookNumber } = item
      item.total = item.bookNumber * item.price
      userApi.cartUpdateNumber(
        { bookId, bookNumber }
      ).then(resp => {

      }, err => {
        console.log(err)
      })
    },
    initData() {
      this.loading = true
      this.userId = this.$store.getters.token
      userApi.getAllCart().then(resp => {
        this.tableData = [] // 清空原有数据
        this.tableData = resp.data.data[this.userId]
        this.loading = false
      }, err => {
        console.log(err)
      })
    },
    addOrder() {
      var order = []
      this.multipleSelection.forEach(data => {
        const { bookId, bookNumber } = data
        order.push({ bookId, bookNumber })
      })
      userApi.createOrder(order).then(async resp => {
        var { notEnoughInventories } = resp.data.data
        if (notEnoughInventories) {
          var books = []
          for (let i = 0; i < notEnoughInventories.length; i++) {
            const bookId = notEnoughInventories[i].bookId
            const bookNumber = notEnoughInventories[i].number
            await userApi.getBookById(bookId).then(resp => {
              var book = resp.data.data[bookId]
              books.push(book.bookName + '剩余' + bookNumber + '本')
            })
          }
          this.$notify({
            title: '库存不足',
            message: JSON.stringify({ 图书: books }) + '，库存暂时不足未生成订单，其余生成成功。',
            position: 'top-left'
          })
        } else {
          this.$message.success('订单生成成功！')
        }
      }, err => {
        this.$message({
          message: '订单生成异常！',
          type: 'error',
          duration: 2000
        })
        console.log(err)
      })
    },
    removeItems() {
      var order = []
      this.multipleSelection.forEach(data => {
        order.push(data.bookId)
      })
      userApi.deleteCart(order).then(resp => {
        resp.data.code === 200 && this.$message.success('删除成功！')
        this.initData()
      }, err => {
        this.$message.danger('删除失败！')
        console.log(err)
      })
    },
    goBack() {
      this.$router.push({ path: '/' })
    }
  }

}
</script>

<style scoped>
.container {
    width: 100%;
    max-width: 1140px;
    padding-right: 15px;
    padding-left: 15px;
    margin-right: auto;
    margin-left: auto;
}
.row {
  display: flex;
  justify-content: space-between;
}
.cart-area {
    margin-top: 30px;
    margin-bottom: 30px;
}
.cart-area .row {
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    align-items: flex-end;
}
.cart-area .Breadcrumb {
  display: flex;
  width: 100%;
  justify-content: flex-start;
}
.cart-area .row .btn {
  display: flex;
  width: 100%;
  justify-content: space-between;
}
</style>
